package com.qf.air.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.UUID;

/**
 * @Author: 维多利加
 * @Date: 2021/3/25 19:39
 */
@RestController
@CrossOrigin(allowCredentials = "true")
public class UploadController {

    @PostMapping("/upload")
    public String upload(MultipartFile pic) throws Exception {
        //1.校验大小，图片要小于5M
        long size = pic.getSize();
        if(size>=5242880){
            //图片大于5M
            return "pic is too big,you need small!!";
        }

        String s = Base64.getEncoder().encodeToString(pic.getBytes());

        //2.校验文件后缀
        String originalFilename = pic.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if(!".JPG".equalsIgnoreCase(suffix)){
            //图片后缀不正确
            return "pic suffix not true,you need upload other pic";
        }

        //3.校验图片是否损坏
        InputStream inputStream = pic.getInputStream();
        BufferedImage image = ImageIO.read(inputStream);
        if(image == null){
            //图片已损坏
            return "pic already broker,you need upload other pic";
        }

        //4.保存到本地
        pic.transferTo(new File("D:\\img\\"+ UUID.randomUUID().toString() + suffix));
        return "pic is upload success";
    }
}
